package com.example.educationai.service.impl;

import com.example.educationai.entity.ClassEntity;
import com.example.educationai.entity.SimpleUser;
import com.example.educationai.repository.ClassRepository;
import com.example.educationai.repository.SimpleUserRepository;
import com.example.educationai.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private ClassRepository classRepository;

    @Autowired
    private SimpleUserRepository simpleUserRepository;

    @Override
    @Transactional
    public SimpleUser addStudentToClass(Long classId, String studentName, String studentId) {
        ClassEntity classEntity = classRepository.findById(classId)
                .orElseThrow(() -> new RuntimeException("班级不存在"));

        // 检查学生是否已存在
        SimpleUser student = simpleUserRepository.findByUsername(studentId)
                .orElseGet(() -> {
                    SimpleUser newStudent = new SimpleUser();
                    newStudent.setUsername(studentId);
                    newStudent.setPassword(studentId); // 默认密码为学生ID
                    newStudent.setRole(SimpleUser.UserRole.STUDENT);
                    return newStudent;
                });

        // 设置学生姓名
        student.setEmail(studentName + "@student.com"); // 临时邮箱

        // 保存学生信息
        student = simpleUserRepository.save(student);

        // 将学生添加到班级
        classEntity.getStudents().add(student);
        // 更新学生数量
        classEntity.setStudentCount(classEntity.getStudents().size());
        classRepository.save(classEntity);

        return student;
    }

    @Override
    @Transactional
    public void removeStudentFromClass(Long classId, Long studentId) {
        ClassEntity classEntity = classRepository.findById(classId)
                .orElseThrow(() -> new RuntimeException("班级不存在"));

        SimpleUser student = simpleUserRepository.findById(studentId)
                .orElseThrow(() -> new RuntimeException("学生不存在"));

        classEntity.getStudents().remove(student);
        // 更新学生数量
        classEntity.setStudentCount(classEntity.getStudents().size());
        classRepository.save(classEntity);
    }

    @Override
    public List<SimpleUser> getClassStudents(Long classId) {
        ClassEntity classEntity = classRepository.findById(classId)
                .orElseThrow(() -> new RuntimeException("班级不存在"));

        return classEntity.getStudents().stream().toList();
    }
} 